#!/bin/bash

set -o errexit
set -o pipefail

export LC_ALL=C

WAIT_TIMEOUT=10 # seconds

NODES_NUM=$1
SYNC_DIR=$2

NODE_STR=$(hostname)_$$_$(date +%s)
NODE_HASH=`echo $NODE_STR | md5sum | awk '{print $1}'`

echo $NODE_STR > $SYNC_DIR/$NODE_HASH
sleep $WAIT_TIMEOUT

if [ ! $(ls $SYNC_DIR | wc -l) -eq $NODES_NUM ]; then
    echo "Not enough files to start" >&2
    exit 1
fi

NODE_ID=0
for fhash in `ls $SYNC_DIR`; do
    if [[ "$fhash" = "$NODE_HASH" ]]; then
        echo $NODE_ID
        exit 0
    fi
    NODE_ID=$(($NODE_ID+1))
done

echo "Current hash was not found" >&2
exit 2
